package com.example.juyixia;

import java.io.BufferedReader;
import java.io.BufferedWriter;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.example.adapter.MyAdapterchecked;
import com.example.mathutil.JuyixiaUtil;
import com.example.service.ActiveService;
import com.example.service.MessService;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import sun.misc.BASE64Decoder;

public class NewActiveActivity extends Activity implements OnClickListener {
	private Button mBt_Sure;
	private ImageView mIv_Back;
	private Myinfo myinfo;
	private TextView datatext;
	private TextView timetext;
	private ListView friends;
	private Map<String, String> ipmap = new HashMap<String, String>();
	static JSONObject actievinfojson;
	List<Map<String, String>> ips = new ArrayList<Map<String, String>>();;
	String rec;
	private int num;// 参与人数
	private static List<Map<String, String>> partlist = new ArrayList<Map<String, String>>();
	public static final String bm = "utf-8";
	StringBuffer setid;
	private EditText activename;
	StringBuffer allip;
	Map<String, String> activeinfo = new HashMap<String, String>();
	private Calendar c;
	private int flag=2;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_newactive);
		 c = Calendar.getInstance();//获得系统当前日期
		friends = (ListView) findViewById(R.id.selectfriend);
		activename = (EditText) findViewById(R.id.activename);
		datatext=(TextView) findViewById(R.id.date);
		timetext=(TextView) findViewById(R.id.time);
		datatext.setOnClickListener(new OnClickListener() {
			
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(R.id.date);
			}
		});
		timetext.setOnClickListener(new OnClickListener() {
			
			@SuppressWarnings("deprecation")
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				showDialog(R.id.time);
			}
		});
		// 给链表添加数据
		List<Map<String, Object>> list = getData();
		// 适配器，刚刚重写的！
		MyAdapterchecked myAdapter = new MyAdapterchecked(this, list);
		// 设置适配器
		friends.setAdapter(myAdapter);
		initViews();

	}

	public List<Map<String, Object>> getData() {
		myinfo = (Myinfo) getApplication();
		List<Myinfo> friendsinfo = myinfo.getUserfriend();
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		for (Myinfo info : friendsinfo) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("image", R.drawable.ic_launcher);
			map.put("userid", info.getUserid());
			map.put("username", info.getUsername());
			map.put("userip", info.getUserip());
			list.add(map);
		}

		return list;
	}

	public boolean isHostConnectable(String host, int port, String currentname) {
		Socket socket = new Socket();
		try {
			socket.connect(new InetSocketAddress(host, port));
			PrintWriter out = new PrintWriter(new BufferedWriter(
					new OutputStreamWriter(socket.getOutputStream(), bm)), true);
			out.println(actievinfojson.toString() + "？" + currentname);
			out.close();

			// 关闭Socket
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return true;

	}

	private void initViews() {
		// TODO Auto-generated method stub
		mBt_Sure = (Button) findViewById(R.id.bt_sure);
		mIv_Back = (ImageView) findViewById(R.id.iv_back);

		mBt_Sure.setOnClickListener(this);
		mIv_Back.setOnClickListener(this);
	}
	 @Override
		protected Dialog onCreateDialog(int id) {
			Dialog dialog = null;
			switch (id) {
			case R.id.date:
				 DatePickerDialog.OnDateSetListener dateListener = new DatePickerDialog.OnDateSetListener() { 
	                 @Override 
	                 public void onDateSet(DatePicker datePicker,int year, int month, int dayOfMonth) { 
	                	 
	                	 if(year>getYear()){	//设置年大于当前年，直接设置，不用判断下面的
	                		 datatext.setText(dayOfMonth + "/"+(month+1)+"/"+year);
	                		 flag = 1;
	                	 }else if(year == getYear()){	//设置年等于当前年，则向下开始判断月
	                		 if((month+1) > getMonth()){	//设置月等于当前月，直接设置，不用判断下面的
	                			 flag = 1;
	                			 datatext.setText(dayOfMonth + "/"+(month+1)+"/"+year);
	                		 }else if((month+1) == getMonth()){		//设置月等于当前月，则向下开始判断日
	                			 if(dayOfMonth > getDay()){			//设置日大于当前月，直接设置，不用判断下面的
	                				 flag = 1;
	                    			 datatext.setText(dayOfMonth + "/"+(month+1)+"/"+year);
	                			 }else if(dayOfMonth == getDay()){	//设置日等于当前日，则向下开始判断时
	                				 flag = 2;
	                    			datatext.setText(dayOfMonth + "/"+(month+1)+"/"+year);
	                			 }else{		//设置日小于当前日，提示重新设置
	                				 flag = 3;
	                				 Toast.makeText(NewActiveActivity.this, "当前日不能小于今日,请重新设置", 2000).show();
	                			 }
	                		 }else{			//设置月小于当前月，提示重新设置
	                			 flag = 3;
	                			 Toast.makeText(NewActiveActivity.this, "当前月不能小于今月，请重新设置", 2000).show();
	                		 }
	                	 }else{				//设置年小于当前年，提示重新设置
	                		 flag = 3;
	                		 Toast.makeText(NewActiveActivity.this, "当前年不能小于今年，请重新设置", 2000).show();
	                	 }
	                	 
	                	 if(flag == 3){
	                		 datePicker.init(getYear(), (getMonth()-1), getDay(), new DatePicker.OnDateChangedListener() {
									
									@Override
									public void onDateChanged(DatePicker view, int year, int monthOfYear,
											int dayOfMonth) {
										datatext.setText(year+"/"+(monthOfYear+1) + "/"+dayOfMonth);
									}
								});
	                	 }
	                 } 
	             }; 
	        	 dialog = new DatePickerDialog(this, dateListener, getYear(), (getMonth()-1), getDay()); 
	             break;
			case R.id.time:
				TimePickerDialog.OnTimeSetListener timeListener = new TimePickerDialog.OnTimeSetListener() {
					
					@Override
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						
						switch (flag) {
						case 1:			//设置日期在当前日期之后，直接设置时间，不用判断
							timetext.setText(hourOfDay+":"+minute);
							break;
						case 2:			//设置日期等于当前日期之后，判断时和分
							if(hourOfDay>getHonor()){
								timetext.setText(hourOfDay+":"+minute);
							}else if(hourOfDay == getHonor()){
								if(minute>getMin()){
									timetext.setText(hourOfDay+":"+minute);
								}else{
									timetext.setText(getHonor()+":"+getMin());
									Toast.makeText(NewActiveActivity.this, "请选择大于现在时刻的分钟", 2000).show();
								}
							}else{
								timetext.setText(getHonor()+":"+getMin());
								Toast.makeText(NewActiveActivity.this, "请选择大于现在时刻的小时", 2000).show();
							}
							break;
						case 3:			//设置日期等于当前日期之前，提示日期还未设置正确，不能设置时间
							timetext.setText(getHonor()+":"+getMin());
							Toast.makeText(NewActiveActivity.this, "请先设置正确的日期", 2000).show();
							break;
						
						default:
							break;
						}
					}
				};
			
				dialog = new TimePickerDialog(this, timeListener, getHonor(),getMin(), true);
				break;
			case 1:
				AlertDialog.Builder builder = new AlertDialog.Builder(NewActiveActivity.this);
				builder.setTitle("您要确定放弃编辑吗？");
				builder.setPositiveButton("确定",new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface arg0, int arg1) {
						NewActiveActivity.this.finish();
					}});
				builder.setNegativeButton("取消",new DialogInterface.OnClickListener() {
					
					public void onClick(DialogInterface dialog,int whichButton) {

					}
				});
				builder.show();
				break;
			default:
				break;
			}
			return dialog;
		}
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

		switch (v.getId()) {
		case R.id.bt_sure:
			num = 0;
			Toast.makeText(getApplicationContext(),"已发送通知给选中好友，请等待回复！",Toast.LENGTH_SHORT).show();
			activeinfo.clear();
			ips.clear();
			ipmap.clear();
			allip = new StringBuffer("");
			setid = new StringBuffer("");
			// ips=new ArrayList<Map<String, String>>();
			for (int i = 0; i < friends.getChildCount(); i++) {
				// Map<String, String> ipmap=new HashMap<String, String>();
				LinearLayout myitem = (LinearLayout) friends.getChildAt(i);
				CheckBox chkone = (CheckBox) myitem
						.findViewById(R.id.friendchecked);
				if (chkone.isChecked()) {
					num++;
					TextView friendsname = (TextView) myitem
							.findViewById(R.id.usersfriendname);
					TextView friendsip = (TextView) myitem
							.findViewById(R.id.usersfriendip);
					ipmap.put("name", friendsname.getText().toString());
					ipmap.put("ip", friendsip.getText().toString());
					ips.add(ipmap);
					if (i < friends.getChildCount() - 1) {
						setid.append(friendsname.getText()).append(",");
						allip.append(friendsip.getText()).append(",");
					} else {
						setid.append(friendsname.getText());
						allip.append(friendsip.getText());
					}
				}

			}
			activeinfo.put("发起人：", myinfo.getUsername());
			activeinfo.put("发起人ip：", myinfo.getUserip());
			activeinfo.put("活动名：", activename.getText().toString());
			activeinfo
					.put("参与者：",
							setid.append(",").append((myinfo.getUsername()))
									.toString());
			activeinfo.put("allip", allip.toString());
			activeinfo.put("活动时间", datatext.getText().toString()+timetext.getText().toString());
			// Toast.makeText(getApplicationContext(),activeinfo.toString(),Toast.LENGTH_SHORT).show();
			actievinfojson = new JSONObject(activeinfo);
			Intent intent = new Intent(this, ActiveService.class);
			intent.putExtra("人数", String.valueOf(num));
			intent.putExtra("id", myinfo.getUserid());
			startService(intent);
			new Thread() {
				public void run() {
					for (Map<String, String> map : ips) {
						if (!isHostConnectable(map.get("ip"), 20000,
								map.get("name"))) {
							continue;
						}
					}
					handler.sendEmptyMessage(0);// 执行完毕后给handler发送一个空消息
				}

				// 定义Handler对象
				private Handler handler = new Handler() {
					@Override
					// 当有消息发送出来的时候就执行Handler的这个方法
					public void handleMessage(Message msg) {
						super.handleMessage(msg);
						// 处理UI
					}
				};
			}.start();
//			Toast.makeText(getApplicationContext(),str,
//					Toast.LENGTH_SHORT).show();
			break;
		case R.id.iv_back:
			finish();

		default:
			break;
		}

	}
	 /**
		 * 得到时间和日期一系列方法
		 * @return
		 */
		public int getYear(){
			return c.get(Calendar.YEAR);
		}

		public int getMonth(){
			return c.get(Calendar.MONTH)+1;//系统日期从0开始算起
		}
		
		public int getDay(){
			return c.get(Calendar.DAY_OF_MONTH);
		}
		
		public int getHonor(){
			return c.get(Calendar.HOUR_OF_DAY);
		}
		
		public int getMin(){
			return c.get(Calendar.MINUTE);
		}
}
